package org.yxing.palpalgps.domain;

import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;
import org.yxing.palpalgps.http.FetchData;

import android.util.Log;

public class UserInfoLoader {
    private static final String TAG = "UserInfoLoader";
    
    private HashMap<String, SimpleUserInfo> cache;
    private FetchData mFetchData;
    
    public UserInfoLoader(FetchData fetchData) {
        cache = new HashMap<String, SimpleUserInfo>();
        mFetchData = fetchData;
    }
    
    public SimpleUserInfo load(String uid) {
        SimpleUserInfo user = null;
        if (cache.containsKey(uid)) {
            user = cache.get(uid);
        } else {
            String data = mFetchData.fetchUserProfile(uid);
            try {
                JSONObject json = new JSONObject(data).getJSONObject("result");
                user = new SimpleUserInfo(uid);
                user.setName(json.getString(UserInfo.KEY_NAME));
                user.setFace(json.getString(UserInfo.KEY_FACE));
                user.setGender(json.getString(UserInfo.KEY_GENDER));
                cache.put(uid, user);
            } catch (JSONException e) {
                Log.w(TAG, e.getMessage());
            }
        }
        return user;
    }
}
